import React, { useState, useEffect } from 'react';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, LineElement, PointElement, Title, Tooltip, Legend, ArcElement } from 'chart.js';
import { Bar, Pie, Line } from 'react-chartjs-2';
import api from '../../services/api';
import './UserPage.css';

// 注册 Chart.js 组件 - 添加了 LineElement 和 PointElement
ChartJS.register(CategoryScale, LinearScale, BarElement, LineElement, PointElement, Title, Tooltip, Legend, ArcElement);

// 确认对话框组件
const ConfirmDialog = ({ isOpen, onClose, onConfirm, title, message, confirmText, cancelText }) => {
    if (!isOpen) return null;

    return (
        <div className="confirm-dialog-overlay">
            <div className="confirm-dialog">
                <h3>{title}</h3>
                <p>{message}</p>
                <div className="confirm-dialog-buttons">
                    <button className="cancel-btn" onClick={onClose}>
                        {cancelText || '取消'}
                    </button>
                    <button className="confirm-btn" onClick={onConfirm}>
                        {confirmText || '确认'}
                    </button>
                </div>
            </div>
        </div>
    );
};

// 风险等级显示组件
const RiskLevel = ({ risk }) => {
    if (risk === null || risk === undefined) {
        return <span className="risk-level unknown">未分析</span>;
    }

    const getRiskLevel = (riskValue) => {
        if (riskValue >= 0.8) return { level: '高风险', className: 'high' };
        if (riskValue >= 0.5) return { level: '中风险', className: 'medium' };
        if (riskValue >= 0.3) return { level: '低风险', className: 'low' };
        return { level: '安全', className: 'safe' };
    };

    const { level, className } = getRiskLevel(risk);

    return (
        <span className={`risk-level ${className}`}>
            {level} ({(risk * 100).toFixed(1)}%)
        </span>
    );
};

// 分析弹窗组件 - 增强版
const AnalyticsDialog = ({ isOpen, onClose, user }) => {
    if (!isOpen || !user) return null;

    return (
        <div className="analytics-dialog-overlay">
            <div className="analytics-dialog">
                <div className="analytics-dialog-header">
                    <h2>{user.username} 的用户行为分析</h2>
                    <button className="close-btn" onClick={onClose}>×</button>
                </div>
                <div className="analytics-dialog-content">
                    {user.analysis && (
                        <div className="analytics-grid">
                            {/* 作弊风险时序折线图 */}
                            {user.analysis.riskTimeSeries && user.analysis.riskTimeSeries.length > 0 && (
                                <div className="analytics-card risk-timeline">
                                    <h3>作弊风险时序分析</h3>
                                    <div className="risk-summary">
                                        <span className="overall-risk">
                                            整体风险评分: <RiskLevel risk={user.analysis.overallRisk} />
                                        </span>
                                        <span className="data-points" style={{marginLeft: '20px', color: '#666'}}>
                                            数据点数量: {user.analysis.riskTimeSeries.length}
                                        </span>
                                    </div>
                                    <Line
                                        data={{
                                            labels: user.analysis.riskTimeSeries.map(item => {
                                                const date = new Date(item.time);
                                                return date.toLocaleDateString('zh-CN', {
                                                    month: '2-digit',
                                                    day: '2-digit',
                                                    hour: '2-digit',
                                                    minute: '2-digit'
                                                });
                                            }),
                                            datasets: [{
                                                label: '作弊风险指数',
                                                data: user.analysis.riskTimeSeries.map(item => item.speed),
                                                borderColor: 'rgba(255, 99, 132, 1)',
                                                backgroundColor: 'rgba(255, 99, 132, 0.1)',
                                                borderWidth: 2,
                                                fill: true,
                                                tension: 0.4,
                                                pointRadius: 4,
                                                pointBackgroundColor: 'rgba(255, 99, 132, 1)',
                                                pointBorderColor: '#fff',
                                                pointBorderWidth: 2
                                            }]
                                        }}
                                        options={{
                                            responsive: true,
                                            maintainAspectRatio: false,
                                            plugins: {
                                                title: {
                                                    display: true,
                                                    text: '用户作弊风险时序变化',
                                                    font: {
                                                        size: 16
                                                    }
                                                },
                                                legend: {
                                                    display: true,
                                                    position: 'top'
                                                },
                                                tooltip: {
                                                    mode: 'index',
                                                    intersect: false,
                                                    callbacks: {
                                                        title: function(context) {
                                                            const dataIndex = context[0].dataIndex;
                                                            const originalTime = user.analysis.riskTimeSeries[dataIndex].time;
                                                            return new Date(originalTime).toLocaleString('zh-CN');
                                                        },
                                                        label: function(context) {
                                                            return `风险指数: ${(context.parsed.y * 100).toFixed(1)}%`;
                                                        }
                                                    }
                                                }
                                            },
                                            scales: {
                                                y: {
                                                    beginAtZero: true,
                                                    max: 1,
                                                    title: {
                                                        display: true,
                                                        text: '风险指数 (0-1)'
                                                    },
                                                    ticks: {
                                                        callback: function(value) {
                                                            return (value * 100).toFixed(0) + '%';
                                                        }
                                                    },
                                                    grid: {
                                                        color: 'rgba(255, 255, 255, 0.1)'
                                                    }
                                                },
                                                x: {
                                                    title: {
                                                        display: true,
                                                        text: '时间'
                                                    },
                                                    grid: {
                                                        color: 'rgba(255, 255, 255, 0.1)'
                                                    },
                                                    ticks: {
                                                        maxTicksLimit: 10,
                                                        callback: function(value, index) {
                                                            const totalTicks = this.getLabelForValue(this.max)?.length || 0;
                                                            if (totalTicks > 10 && index % Math.ceil(totalTicks / 10) !== 0) {
                                                                return '';
                                                            }
                                                            return this.getLabelForValue(value);
                                                        }
                                                    }
                                                }
                                            },
                                            interaction: {
                                                mode: 'nearest',
                                                axis: 'x',
                                                intersect: false
                                            }
                                        }}
                                    />
                                </div>
                            )}

                            {/* IP地址记录 */}
                            {user.analysis.ipList && user.analysis.ipList.length > 0 && (
                                <div className="analytics-card">
                                    <h3>用户IP地址记录</h3>
                                    <div className="ip-list">
                                        {user.analysis.ipList.map((ip, index) => (
                                            <span key={index} className="ip-item">
                                                {ip}
                                            </span>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {/* 下载偏好分析 */}
                            {user.analysis.downloadPreferences && user.analysis.downloadPreferences.length > 0 && (
                                <div className="analytics-card">
                                    <h3>下载偏好分析</h3>
                                    <Pie
                                        data={{
                                            labels: user.analysis.downloadPreferences.map(item => item.tag.content),
                                            datasets: [{
                                                data: user.analysis.downloadPreferences.map(item => item.usageCount),
                                                backgroundColor: [
                                                    'rgba(255, 99, 132, 0.5)',
                                                    'rgba(54, 162, 235, 0.5)',
                                                    'rgba(255, 206, 86, 0.5)',
                                                    'rgba(75, 192, 192, 0.5)',
                                                    'rgba(153, 102, 255, 0.5)',
                                                    'rgba(255, 159, 64, 0.5)'
                                                ],
                                                borderColor: [
                                                    'rgba(255, 99, 132, 1)',
                                                    'rgba(54, 162, 235, 1)',
                                                    'rgba(255, 206, 86, 1)',
                                                    'rgba(75, 192, 192, 1)',
                                                    'rgba(153, 102, 255, 1)',
                                                    'rgba(255, 159, 64, 1)'
                                                ],
                                                borderWidth: 1
                                            }]
                                        }}
                                        options={{
                                            responsive: true,
                                            plugins: {
                                                legend: {
                                                    position: 'right',
                                                    labels: {
                                                        font: {
                                                            size: 12
                                                        }
                                                    }
                                                },
                                                title: {
                                                    display: true,
                                                    text: '用户下载偏好',
                                                    font: {
                                                        size: 16
                                                    }
                                                }
                                            }
                                        }}
                                    />
                                </div>
                            )}

                            {/* 活跃时间段分析 */}
                            {user.analysis.activeDegrees && user.analysis.activeDegrees.length > 0 && (
                                <div className="analytics-card">
                                    <h3>活跃时间段分析</h3>
                                    <Bar
                                        data={{
                                            labels: user.analysis.activeDegrees.map(item =>
                                                new Date(item.time).toLocaleDateString('zh-CN', {
                                                    month: 'numeric',
                                                    day: 'numeric',
                                                    hour: '2-digit',
                                                })
                                            ),
                                            datasets: [{
                                                label: '用户活跃度',
                                                data: user.analysis.activeDegrees.map(item => item.speed),
                                                backgroundColor: 'rgba(54, 162, 235, 0.5)',
                                                borderColor: 'rgba(54, 162, 235, 1)',
                                                borderWidth: 1
                                            }]
                                        }}
                                        options={{
                                            responsive: true,
                                            plugins: {
                                                title: {
                                                    display: true,
                                                    text: '用户活跃时间段分析'
                                                },
                                                legend: {
                                                    display: true
                                                }
                                            },
                                            scales: {
                                                y: {
                                                    beginAtZero: true,
                                                    title: {
                                                        display: true,
                                                        text: '活跃度'
                                                    }
                                                },
                                                x: {
                                                    title: {
                                                        display: true,
                                                        text: '时间'
                                                    }
                                                }
                                            }
                                        }}
                                    />
                                </div>
                            )}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

const UserPage = ({ user, token }) => {
    const [users, setUsers] = useState([]);
    const [selectedUser, setSelectedUser] = useState(null);
    const [isAdmin, setIsAdmin] = useState(false);
    const [showAnalytics, setShowAnalytics] = useState(false);
    const [loading, setLoading] = useState(true);
    const [message, setMessage] = useState({ type: '', text: '' });

    // 分页相关状态
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);

    // 存储用户风险评分
    const [userRisks, setUserRisks] = useState({});

    const [confirmDialog, setConfirmDialog] = useState({
        isOpen: false,
        title: '',
        message: '',
        confirmText: '',
        onConfirm: null
    });

    // 添加 token 提取逻辑 - 从个人中心页面复制
    const actualToken = (() => {
        let extractedToken = null;

        // 首先检查传入的 token 是否有效
        if (token && token !== 'undefined' && token !== 'null' && token.trim() !== '') {
            extractedToken = token.trim();
        }
        // 如果传入的 token 无效，尝试从 user.data.token 中提取
        else if (user?.data?.token) {
            extractedToken = user.data.token.trim();
        }
        // 最后尝试从 localStorage 获取
        else {
            const localToken = localStorage.getItem('token');
            if (localToken && localToken !== 'undefined' && localToken !== 'null' && localToken.trim() !== '') {
                extractedToken = localToken.trim();
            }
        }

        // 验证 token 格式
        if (extractedToken) {
            console.log('=== 用户管理页面 Token 验证 ===');
            console.log('提取到的 token:', extractedToken);
            console.log('Token 长度:', extractedToken.length);
            console.log('Token 开头:', extractedToken.substring(0, 20));
            console.log('Token 结尾:', extractedToken.substring(extractedToken.length - 20));

            // 检查是否是有效的 JWT 格式 (应该有两个点分隔三部分)
            const parts = extractedToken.split('.');
            console.log('Token 分段数量:', parts.length);

            if (parts.length !== 3) {
                console.error('Token 格式不正确，应该有3个部分，实际有:', parts.length);
                return null;
            }

            // 检查每个部分是否是有效的 base64
            for (let i = 0; i < parts.length; i++) {
                if (!parts[i] || parts[i].length === 0) {
                    console.error(`Token 第${i+1}部分为空`);
                    return null;
                }
            }

            console.log('✅ Token 验证通过');
            return extractedToken;
        }

        console.error('❌ 无法获取有效的 Token');
        return null;
    })();

    // 获取用户列表
    const fetchUsers = async () => {
        if (!actualToken) {
            console.error('❌ 无法获取用户列表：缺少有效的Token');
            setMessage({
                type: 'error',
                text: '缺少认证信息，请重新登录'
            });
            setLoading(false);
            return;
        }

        try {
            setLoading(true);
            console.log('=== 获取用户列表 ===');
            console.log('使用的 token:', actualToken.substring(0, 20) + '...');

            const response = await api.getUserAdminList(actualToken, currentPage, pageSize);

            if (response.data) {
                setUsers(response.data || []);
                setTotal(response.data.total || 0);

                // 异步获取每个用户的风险评分
                fetchUsersRisk(response.data || [], actualToken);
            }
        } catch (error) {
            console.error('❌ 获取用户列表失败:', error);
            setMessage({
                type: 'error',
                text: error.message || '获取用户列表失败'
            });
        } finally {
            setLoading(false);
        }
    };

    // 获取用户风险评分
    const fetchUsersRisk = async (userList, token) => {
        if (!token) {
            console.warn('⚠️ 无法获取用户风险评分：缺少Token');
            return;
        }

        const riskPromises = userList.map(async (user) => {
            try {
                console.log(`🔍 获取用户${user.userId}的风险评分...`);
                const response = await api.getAnalysisResult(token, user.userId);
                if (response.status === 1 && response.data) {
                    console.log(`✅ 用户${user.userId}风险评分:`, response.data.overallRisk);
                    return {
                        userId: user.userId,
                        overallRisk: response.data.overallRisk
                    };
                }
            } catch (error) {
                console.warn(`⚠️ 获取用户${user.userId}风险评分失败:`, error.message);
            }
            return {
                userId: user.userId,
                overallRisk: null
            };
        });

        try {
            const risks = await Promise.all(riskPromises);
            const riskMap = {};
            risks.forEach(risk => {
                riskMap[risk.userId] = risk.overallRisk;
            });
            console.log('✅ 批量获取用户风险评分完成:', riskMap);
            setUserRisks(riskMap);
        } catch (error) {
            console.error('❌ 批量获取用户风险评分失败:', error);
        }
    };

    // 初始加载和依赖变化时获取数据
    useEffect(() => {
        console.log('=== UserPage useEffect 触发 ===');
        console.log('Props:', { user: !!user, token: !!token });
        console.log('实际使用的 token:', actualToken ? '有效' : '无效');

        if (actualToken) {
            fetchUsers();
        } else {
            console.error('❌ Token无效，无法加载用户数据');
            setMessage({
                type: 'error',
                text: '缺少认证信息，请重新登录'
            });
            setLoading(false);
        }
    }, [actualToken, currentPage, pageSize]); // 依赖改为 actualToken

    // 处理封禁/解封用户
    const handleBanUser = async (userId, isBanned) => {
        if (!actualToken) {
            setMessage({
                type: 'error',
                text: '缺少认证信息，请重新登录'
            });
            return;
        }

        setConfirmDialog({
            isOpen: true,
            title: !isBanned ? '确认封禁用户' : '确认解除封禁',
            message: !isBanned
                ? '确定要封禁该用户吗？封禁后用户将无法登录系统。'
                : '确定要解除该用户的封禁状态吗？',
            confirmText: !isBanned ? '确认封禁' : '确认解除',
            onConfirm: async () => {
                try {
                    console.log(`=== ${!isBanned ? '封禁' : '解封'}用户 ===`);
                    console.log('用户ID:', userId);
                    console.log('当前状态:', isBanned ? '已封禁' : '活跃');

                    let response;

                    if (!isBanned) {
                        response = await api.banned(actualToken, userId);
                    } else {
                        response = await api.unbanned(actualToken, userId);
                    }

                    if (response.status === 1) {
                        const successMessage = !isBanned ? '用户已封禁' : '用户已解封';
                        console.log('✅', successMessage);
                        setMessage({
                            type: 'success',
                            text: successMessage
                        });
                        // 刷新用户列表
                        fetchUsers();
                    }
                } catch (error) {
                    console.error('❌ 操作失败:', error);
                    setMessage({
                        type: 'error',
                        text: error.message || '操作失败，请重试'
                    });
                } finally {
                    setConfirmDialog({ ...confirmDialog, isOpen: false });
                }
            }
        });
    };

    // 查看用户分析 - 增强版
    const handleViewAnalytics = async (user) => {
        if (!actualToken) {
            setMessage({
                type: 'error',
                text: '缺少认证信息，请重新登录'
            });
            return;
        }

        try {
            console.log('=== 查看用户分析 ===');
            console.log('用户:', user.username, '(ID:', user.userId, ')');

            const response = await api.getAnalysisResult(actualToken, user.userId);
            const favoriteTagsRes = await api.getFavoriteTags(actualToken, user.userId, 5);

            if (response.status === 1) {
                let riskTimeSeries = [];
                let overallRisk = null;
                let ipList = [];

                if (response.data) {
                    overallRisk = response.data.overallRisk;
                    console.log('整体风险评分:', overallRisk);

                    // 增强的 details 字段解析
                    if (response.data.details) {
                        try {
                            console.log('原始details数据:', response.data.details);

                            // 处理可能的字符串转义问题
                            let detailsStr = response.data.details;
                            if (typeof detailsStr === 'string') {
                                // 如果是双重转义的JSON字符串，先解析一次
                                if (detailsStr.startsWith('"') && detailsStr.endsWith('"')) {
                                    detailsStr = JSON.parse(detailsStr);
                                }
                            }

                            const details = typeof detailsStr === 'string' ? JSON.parse(detailsStr) : detailsStr;
                            console.log('解析后的details对象:', details);

                            // 解析 speed_samples 时序数据
                            if (details.speed_samples && Array.isArray(details.speed_samples)) {
                                riskTimeSeries = details.speed_samples
                                    .filter(item => item && item.time && typeof item.speed === 'number')
                                    .map(item => ({
                                        time: item.time,
                                        speed: Math.max(0, Math.min(1, item.speed)) // 确保speed在0-1范围内
                                    }))
                                    .sort((a, b) => new Date(a.time) - new Date(b.time)); // 按时间排序

                                console.log('处理后的时序数据条数:', riskTimeSeries.length);
                                console.log('时序数据示例:', riskTimeSeries.slice(0, 3));
                            } else {
                                console.warn('⚠️ speed_samples 数据不存在或格式不正确');
                            }

                            // 解析 IP 列表
                            if (details.ip_list && Array.isArray(details.ip_list)) {
                                ipList = details.ip_list;
                                console.log('IP列表:', ipList);
                            }

                        } catch (parseError) {
                            console.error('❌ 解析details字段失败:', parseError);
                            console.error('原始details内容:', response.data.details);

                            // 尝试手动修复常见的JSON格式问题
                            try {
                                let fixedDetails = response.data.details
                                    .replace(/\\/g, '') // 移除转义字符
                                    .replace(/"{/g, '{') // 修复开头的引号
                                    .replace(/}"/g, '}'); // 修复结尾的引号

                                const details = JSON.parse(fixedDetails);
                                console.log('手动修复后解析成功:', details);

                                if (details.speed_samples && Array.isArray(details.speed_samples)) {
                                    riskTimeSeries = details.speed_samples
                                        .filter(item => item && item.time && typeof item.speed === 'number')
                                        .map(item => ({
                                            time: item.time,
                                            speed: Math.max(0, Math.min(1, item.speed))
                                        }))
                                        .sort((a, b) => new Date(a.time) - new Date(b.time));
                                }

                                if (details.ip_list && Array.isArray(details.ip_list)) {
                                    ipList = details.ip_list;
                                }
                            } catch (fixError) {
                                console.error('❌ 手动修复也失败了:', fixError);
                            }
                        }
                    }
                }

                const favoriteTagsData = favoriteTagsRes.data ? favoriteTagsRes.data : [];
                console.log('偏好标签数据:', favoriteTagsData);

                setSelectedUser({
                    ...user,
                    analysis: {
                        overallRisk: overallRisk,
                        riskTimeSeries: riskTimeSeries,
                        activeDegrees: riskTimeSeries, // 使用相同的数据源，也可以分开处理
                        downloadPreferences: favoriteTagsData,
                        ipList: ipList // 新增IP列表数据
                    }
                });
                setShowAnalytics(true);
                console.log('✅ 用户分析数据加载完成');
            }
        } catch (error) {
            console.error('❌ 获取用户分析数据失败:', error);
            setMessage({
                type: 'error',
                text: error.message || '获取用户分析数据失败'
            });
        }
    };

    // 分析用户行为
    const handleAnalyzeUser = async () => {
        if (!actualToken) {
            setMessage({
                type: 'error',
                text: '缺少认证信息，请重新登录'
            });
            return;
        }

        try {
            setLoading(true);
            console.log('=== 启动用户行为分析 ===');

            const response = await api.bootCheatAnalysis(actualToken);

            if (response.status === 1) {
                console.log('✅ 用户行为分析已启动');
                setMessage({
                    type: 'success',
                    text: '用户行为分析已启动'
                });
                // 刷新用户列表
                fetchUsers();
            }
        } catch (error) {
            console.error('❌ 启动用户行为分析失败:', error);
            setMessage({
                type: 'error',
                text: error.message || '启动用户行为分析失败'
            });
        } finally {
            setLoading(false);
        }
    };

    // 处理分页变化
    const handlePageChange = (newPage) => {
        setCurrentPage(newPage);
    };

    // 处理每页数量变化
    const handlePageSizeChange = (event) => {
        setPageSize(Number(event.target.value));
        setCurrentPage(1); // 重置到第一页
    };

    return (
        <div className="user-page">
            <div className="user-header">
                <div className="user-title">
                    <h1>用户管理</h1>
                    <p>管理系统用户，查看用户行为分析</p>
                </div>
                <button
                    className="action-btn analyze-btn"
                    onClick={handleAnalyzeUser}
                >
                    🔍 分析用户行为
                </button>
            </div>

            {message.text && (
                <div className={`message ${message.type}`}>
                    {message.text}
                </div>
            )}

            {loading ? (
                <div className="loading">加载中...</div>
            ) : (
                <>
                    <div className="user-list">
                        {users.map(user => (
                            <div key={user.userId} className="user-card">
                                <div className="user-info">
                                    <div className="user-avatar">
                                        {user.username[0].toUpperCase()}
                                    </div>
                                    <div className="user-details">
                                        <div className="user-name-section">
                                            <h3>{user.username}</h3>
                                            <RiskLevel risk={userRisks[user.userId]} />
                                        </div>
                                        <p>{user.email}</p>
                                        <span className={`user-status ${user.isBanned ? 'banned' : 'active'}`}>
                                            {!user.isBanned ? '活跃' : '已封禁'}
                                        </span>
                                    </div>
                                </div>
                                <div className="user-actions">
                                    <button
                                        className={`action-btn ${user.isBanned ? 'unban-btn' : 'ban-btn'}`}
                                        onClick={() => handleBanUser(user.userId, user.isBanned)}
                                    >
                                        {user.isBanned ? '解除封禁' : '封禁用户'}
                                    </button>
                                    <button
                                        className="action-btn analytics-btn"
                                        onClick={() => handleViewAnalytics(user)}
                                    >
                                        查看分析报告
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>

                    {/* 分页控件 */}
                    <div className="pagination">
                        <div className="page-size-selector">
                            每页显示：
                            <select value={pageSize} onChange={handlePageSizeChange}>
                                <option value={5}>5</option>
                                <option value={10}>10</option>
                                <option value={20}>20</option>
                                <option value={50}>50</option>
                            </select>
                        </div>
                        <div className="page-numbers">
                            <button
                                onClick={() => handlePageChange(currentPage - 1)}
                                disabled={currentPage === 1}
                            >
                                上一页
                            </button>
                            <span>第 {currentPage} 页</span>
                            <button
                                onClick={() => handlePageChange(currentPage + 1)}
                                disabled={currentPage * pageSize >= total}
                            >
                                下一页
                            </button>
                        </div>
                    </div>

                    {/* 分析弹窗 */}
                    <AnalyticsDialog
                        isOpen={showAnalytics}
                        onClose={() => setShowAnalytics(false)}
                        user={selectedUser}
                    />

                    {/* 确认对话框 */}
                    <ConfirmDialog
                        isOpen={confirmDialog.isOpen}
                        onClose={() => setConfirmDialog({ ...confirmDialog, isOpen: false })}
                        onConfirm={confirmDialog.onConfirm}
                        title={confirmDialog.title}
                        message={confirmDialog.message}
                        confirmText={confirmDialog.confirmText}
                    />
                </>
            )}
        </div>
    );
};

export default UserPage;